<template>
  <div class="resources-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>资料库</span>
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio-button label="文件列表">资料列表</el-radio-button>
            <el-radio-button label="下载记录">下载记录</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <!-- 资料文件列表 -->
      <div v-if="activeTab === '文件列表'">
        <el-row :gutter="20" class="filter-row">
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索文件名"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="filterCategory"
              placeholder="文件分类"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="filterType"
              placeholder="文件类型"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="item in fileTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-row>
        
        <el-table :data="filteredFiles" style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="文件名" min-width="220">
            <template #default="scope">
              <div class="file-info">
                <el-icon class="file-icon">
                  <component :is="getFileIcon(scope.row.type)" />
                </el-icon>
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="120" />
          <el-table-column prop="size" label="大小" width="100" />
          <el-table-column prop="type" label="格式" width="100" />
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column prop="downloadCount" label="下载次数" width="100" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                :disabled="!scope.row.canDownload" 
                @click="downloadFile(scope.row)"
              >
                <el-icon><Download /></el-icon> 下载
              </el-button>
              <el-popover
                placement="top"
                width="200"
                trigger="hover"
                :content="getFileDescription(scope.row)"
              >
                <template #reference>
                  <el-button link>
                    <el-icon><InfoFilled /></el-icon>
                  </el-button>
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalFiles"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </div>
      
      <!-- 下载记录列表 -->
      <div v-else>
        <el-table :data="downloadHistory" style="width: 100%">
          <el-table-column prop="fileName" label="文件名" min-width="200" />
          <el-table-column prop="fileType" label="文件类型" width="100" />
          <el-table-column prop="fileSize" label="文件大小" width="100" />
          <el-table-column prop="downloadTime" label="下载时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="savePath" label="保存位置" min-width="200" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                @click="redownloadFile(scope.row)"
                :disabled="scope.row.status === '失败'"
              >
                重新下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 下载确认对话框 -->
    <el-dialog
      v-model="showDownloadDialog"
      title="下载确认"
      width="500px"
    >
      <div>
        <p>您确定要下载以下文件吗？</p>
        <el-descriptions border :column="1">
          <el-descriptions-item label="文件名">{{ currentFile.name }}</el-descriptions-item>
          <el-descriptions-item label="大小">{{ currentFile.size }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ currentFile.type }}</el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ currentFile.uploadTime }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="downloadChecking" class="checking-permission">
          <el-progress :percentage="checkProgress || 0" :format="progressFormat" />
          <p>{{ checkStatusText }}</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDownloadDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmDownload"
            :disabled="downloadChecking || !hasPermission"
          >
            确认下载
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Download, 
  Search, 
  InfoFilled, 
  VideoCameraFilled, 
  PictureFilled, 
  DataLine 
} from '@element-plus/icons-vue'
import { studentApi } from '@/api'

// 当前活动标签
const activeTab = ref('文件列表')

// 搜索和筛选
const searchKeyword = ref('')
const filterCategory = ref('')
const filterType = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalFiles = ref(0)

// 加载状态
const loading = ref(false)

// 下载弹窗控制
const showDownloadDialog = ref(false)
const currentFile = ref({})
const downloadChecking = ref(false)
const checkProgress = ref(0)
const checkStatusText = ref('')
const hasPermission = ref(true)

// 文件分类
const categories = [
  { label: '教学资料', value: '教学资料' },
  { label: '实验指导', value: '实验指导' },
  { label: '教材电子版', value: '教材电子版' },
  { label: '课件', value: '课件' },
  { label: '参考书目', value: '参考书目' }
]

// 文件类型
const fileTypes = [
  { label: 'PDF', value: 'pdf' },
  { label: 'DOC/DOCX', value: 'doc' },
  { label: 'PPT/PPTX', value: 'ppt' },
  { label: 'XLS/XLSX', value: 'xls' },
  { label: 'ZIP/RAR', value: 'zip' },
  { label: '视频', value: 'video' },
  { label: '图片', value: 'image' }
]

// 文件数据
const fileList = ref([])

// 下载历史
const downloadHistory = ref([])

// 获取资源列表
const fetchResourceList = async () => {
  loading.value = true
  try {
    const res = await studentApi.getResources({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      category: filterCategory.value,
      type: filterType.value
    })
    
    if (res.code === 200 && res.data) {
      fileList.value = res.data.list || []
      totalFiles.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取资源列表失败:', error)
    ElMessage.error('获取资源列表失败')
  } finally {
    loading.value = false
  }
}

// 获取下载历史
const fetchDownloadHistory = async () => {
  try {
    const res = await studentApi.getDownloadHistory()
    if (res.code === 200 && res.data) {
      downloadHistory.value = res.data
    }
  } catch (error) {
    console.error('获取下载历史失败:', error)
    ElMessage.error('获取下载历史失败')
  }
}

// 根据筛选条件过滤文件列表
const filteredFiles = computed(() => {
  return fileList.value
})

// 获取文件图标
const getFileIcon = (type) => {
  switch (type) {
    case 'pdf':
    case 'doc':
    case 'xls':
      return 'Document'
    case 'ppt':
      return 'DataLine'
    case 'video':
      return 'VideoCameraFilled'
    case 'image':
      return 'PictureFilled'
    default:
      return 'Document'
  }
}

// 获取文件描述
const getFileDescription = (file) => {
  return file.description || '暂无描述'
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchResourceList()
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchResourceList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchResourceList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchResourceList()
}

// 处理标签切换
const handleTabChange = (tab) => {
  if (tab === '下载记录') {
    fetchDownloadHistory()
  } else {
    fetchResourceList()
  }
}

// 下载文件
const downloadFile = (file) => {
  currentFile.value = file
  showDownloadDialog.value = true
  
  // 模拟检查下载权限
  downloadChecking.value = true
  checkProgress.value = 0
  checkStatusText.value = '正在检查下载权限...'
  hasPermission.value = true
  
  const timer = setInterval(() => {
    checkProgress.value += 10
    if (checkProgress.value >= 100) {
      clearInterval(timer)
      downloadChecking.value = false
      checkStatusText.value = '您有权限下载此文件'
      hasPermission.value = file.canDownload
      
      if (!hasPermission.value) {
        checkStatusText.value = '您没有权限下载此文件'
      }
    }
  }, 200)
}

// 确认下载
const confirmDownload = async () => {
  try {
    const res = await studentApi.downloadResource(currentFile.value.id)
    if (res.code === 200) {
      ElMessage.success('文件开始下载')
      showDownloadDialog.value = false
      
      // 刷新下载历史
      if (activeTab.value === '下载记录') {
        fetchDownloadHistory()
      }
    }
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

// 重新下载文件
const redownloadFile = async (record) => {
  try {
    const res = await studentApi.redownloadResource(record.id)
    if (res.code === 200) {
      ElMessage.success('文件开始重新下载')
      
      // 刷新下载历史
      fetchDownloadHistory()
    }
  } catch (error) {
    console.error('重新下载文件失败:', error)
    ElMessage.error('重新下载文件失败')
  }
}

// 进度条格式化
const progressFormat = (percentage) => {
  return `${percentage}%`
}

// 初始化
onMounted(() => {
  fetchResourceList()
})
</script>

<style scoped>
.resources-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-row {
  margin-bottom: 20px;
}

.file-info {
  display: flex;
  align-items: center;
}

.file-icon {
  margin-right: 8px;
  font-size: 18px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.checking-permission {
  margin: 20px 0;
}
</style> 